from flask import Blueprint, request

from model.model import *
from datetime import datetime
from db_init import db
from tools.tools import item2dict, my_route

order = Blueprint('order', __name__)


# 创建订单
@order.route('/order/<int:h_id>', methods=['POST'])
def add_order(h_id):
    uid = request.args.get('uid')
    hid = House.query.filter_by(id=h_id).first()
    u_id = User.query.filter_by(id=uid).first()
    data = request.form
    s_time = datetime.strptime(data.get('start_t'), '%Y-%m-%d %H:%M:%S').timestamp()
    e_time = datetime.strptime(data.get('end_t'), '%Y-%m-%d %H:%M:%S').timestamp()
    db.session.add(Order(name=data.get('name'), number_id=data.get('number_id'), tenant_id=u_id.id, house_id=hid.id,
                         start_t=s_time, end_t=e_time))
    db.session.commit()
    return {'msg': '订单创建成功', 'code': 200}


# 获取订单
@order.route('/order/<int:h_id>', methods=['GET'])
def get_orders(h_id):
    orders = Order.query.filter_by(house_id=h_id).all()
    now_time = datetime.now().timestamp()
    house_order = []
    for i in orders:
        if i.end_t > int(now_time):
            house_order.append(item2dict(i))
    return my_route(200, house_order)


# 修改状态
@order.route('/<int:o_id>', methods=['PUT'])
def put_order(o_id):
    data = request.form
    Order.query.filter_by(id=o_id).update(data)
    db.session.commit()
    return {'msg': '修改成功', 'code': 200}